import React, { useEffect, useState } from 'react';
import { Steps, Card, Button, Row, Col, Form, message, Alert, Modal, Spin } from 'antd';
import AddressDetails from './components/AddressDetails';
import QuoteInfo from './components/QuoteInfo';
import AddressSelection from './components/AddressSelection';
import PackageInfo from './components/PackageInfo';
import ProductSelect from './components/ProductSelect';
import { TruckPreOrder } from '../types';
import { validateOrder, validateOrderAddress } from './components/validator';
import dayjs from 'dayjs';
import { quotation, saveOrder } from '@/services/order/order_api';
import { FormattedMessage, useIntl } from '@umijs/max';
import { history } from 'umi';

const { Step } = Steps;

const CreateOrderPage: React.FC = () => {
  const [currentStep, setCurrentStep] = useState(0);
  const now = dayjs();
  const nextHour = now.add(1, 'hour').startOf('hour');
  const [submitting, setSubmitting] = useState(false);
  const [canSubmit, setCanSubmit] = useState<boolean>(false);
  const [dataChanged, setDataChanged] = useState<boolean>(false);


  const intl = useIntl();
  const [form] = Form.useForm();
  const [validationErrors, setValidationErrors] = useState<string[]>([]);
  const [showValidationAlert, setShowValidationAlert] = useState(false);

  const DEFAULT_ORDER_INFO = {
    productCode: '',
    referenceNo: '',
    shipperAddressDT: '',
    deliveryAddressDT: '',
    pickReadyDatetime: nextHour.format('YYYY-MM-DD HH:mm'),
    boxs: [{
      boxUnit: 'Box',
      boxQuantity: null,
      boxLength: null,
      boxWidth: null,
      boxHeight: null,
      boxWeight: null,
      boxWeightUnit: 'lbs',
      boxLengthUnit: 'inches',
    }],
    shipperAddress: {
      oaCompany: '',
      oaEmail: '',
      oaPostcode: '',
      oaTelphone: '',
      oaTelphoneExtension: '',
      oaFirstname: '',
      oaLastname: '',
      referenceNo: '',
      note: '_',
    },
    deliveryAddress: {
      oaCompany: '',
      oaEmail: '',
      oaPostcode: '',
      oaTelphone: '',
      oaTelphoneExtension: '',
      oaFirstname: '',
      oaLastname: '',
      referenceNo: '',
      note: '_'
    },
    quote: {}
  };

  const [formData, setFormData] = useState<TruckPreOrder>(DEFAULT_ORDER_INFO);

  const handleFormData = (data: any) => {
    setFormData(data);
  };
  const handleSubmitting = (submitting: boolean) => {
    setSubmitting(submitting);
  }

  const handleValuesChange = (changedValues: any) => {
    setFormData(prev => ({
      ...prev,
      ...changedValues
    }));
  };

  useEffect(() => {
    if(formData.quote){
      setCanSubmit(true);
    }else{
      setCanSubmit(false);
    }
  }, [formData.quote]);

  // 在步骤切换时同步表单值
  useEffect(() => {
    form.setFieldsValue(formData);
  }, [currentStep]);

  const submitOrder = async () => {

    const isValid = await validateQuoteOrder();
    if (!isValid) {
      return;
    }
    setSubmitting(true);
    try {
      const response = await saveOrder(formData);
      if (response.code != 0) {
        let errorMsg = response.msg || intl.formatMessage({ id: "request.error.create" });

        Modal.error({
          title: intl.formatMessage({ id: 'pages.order.create.failed' }),
          content: errorMsg,
          okText: intl.formatMessage({ id: 'pages.button.understand' }),
          onOk: () => console.log('User confirmed error'),
        });
        return;
      }
      Modal.success({
        title: intl.formatMessage({ id: 'pages.order.create.success' }),
        content: intl.formatMessage({ id: 'pages.order.create.success.message' }),
        okText: intl.formatMessage({ id: 'pages.order.create.continue' }),
        cancelText: intl.formatMessage({ id: 'pages.button.backToList' }),
        onOk: () => {
          setFormData(DEFAULT_ORDER_INFO);
          form.resetFields();
          setCurrentStep(0);
        },
        onCancel: () => {
          // 跳转到订单列表页（假设路由为/orders）
          history.push('/order/list');
        },
        okCancel: true
      });
    } catch (error) {
      Modal.error({
        title: intl.formatMessage({ id: 'pages.order.create.systemError' }),
        content: error.message || intl.formatMessage({ id: "request.error.retry" }),
      });
    } finally {
      setSubmitting(false);
    }
  };

  const nextStep = async () => {
    try {
      const isValid = await validateCurrentStep();
      if (!isValid) {
        return;
      }
      // 验证当前表单
      // 验证通过才进入下一步
      setCurrentStep(currentStep + 1);
      setShowValidationAlert(false);
    } catch (error) {
      message.error(intl.formatMessage({ id: 'pages.order.validation.checkForm' }));
    }
  };

  const validateQuoteOrder = async () => {

    try {
      const errors: string[] = [];

      // 验证当前步骤的表单
      if (form && form.internalForms) {
        for (const internalForm of form.internalForms) {
          try {
            await internalForm.validateFields();
          } catch (error) {
            if (error.errorFields && error.errorFields.length > 0) {
              error.errorFields.forEach((field: any) => {
                if (!errors.includes(field.errors[0])) {
                  errors.push(field.errors[0]);
                }
              });
            }
          }
        }
      }
      validateOrder(formData, errors, intl);
      validateOrderAddress(formData, errors, intl);
      if (errors.length > 0) {
        setValidationErrors(errors);
        setShowValidationAlert(true);
        return false;
      }

      setShowValidationAlert(false);
      return true;
    } catch (error) {
      console.error('Validation error:', error);
      return false;
    }
  }
  const validateCurrentStep = async () => {
    try {
      const errors: string[] = [];

      // 验证当前步骤的表单
      if (form && form.internalForms) {
        for (const internalForm of form.internalForms) {
          try {
            await internalForm.validateFields();
          } catch (error) {
            if (error.errorFields && error.errorFields.length > 0) {
              error.errorFields.forEach((field: any) => {
                if (!errors.includes(field.errors[0])) {
                  errors.push(field.errors[0]);
                }
              });
            }
          }
        }
      }
      validateOrder(formData, errors, intl);
      if (errors.length > 0) {
        setValidationErrors(errors);
        setShowValidationAlert(true);
        return false;
      }
      setShowValidationAlert(false);
      return true;
    } catch (error) {
      console.error('Validation error:', error);
      return false;
    }
  };

  const prevStep = () => {
    setCurrentStep(currentStep - 1);
    setFormData(prev => ({
      ...prev,
      quote: undefined
    }));
    setSubmitting(formData.quote?.id ? false : true);
  };

  const steps = [
    {
      title: intl.formatMessage({ id: 'pages.order.steps.basicInfo' }),
      content: (
        <Row gutter={16} style={{ height: '100%' }}>
          <Col span={24} style={{ height: '100%', overflowY: 'auto' }}>
            <Form form={form} onValuesChange={handleValuesChange}>
              <ProductSelect form={form} formData={formData} setFormData={handleFormData} />
              <AddressSelection form={form} formData={formData} setFormData={handleFormData} />
              <PackageInfo form={form} formData={formData} setFormData={handleFormData} />
            </Form>
          </Col>
        </Row>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.order.steps.detailInfo' }),
      content: (
        <Row gutter={16} style={{ height: '100%' }}>
          <Col span={18} style={{ height: '100%', overflowY: 'auto' }}>
            <AddressDetails form={form} formData={formData} setFormData={handleFormData} />
          </Col>
          <Col span={6} style={{ height: '100%', position: 'sticky', top: 0, overflowY: 'auto' }}>
            <QuoteInfo formData={formData} setFormData={handleFormData} setDataChange={setDataChanged} />
          </Col>
        </Row>
      ),
    }
  ];

  return (
    <div style={{
      padding: '24px',
      display: 'flex',
      flexDirection: 'column',
      height: 'calc(100vh - 48px)',
      boxSizing: 'border-box',
      overflow: 'hidden',
      position: 'relative'
    }}>
      <Card style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
        position: 'relative'
      }}>
        <Spin
          spinning={submitting}
          tip={intl.formatMessage({ id: 'pages.order.submitting' })}
          size="large"
          style={{ maxHeight: 'unset' }}
        ></Spin>
        <Steps current={currentStep}>
          {steps.map(item => (
            <Step key={item.title} title={item.title} />
          ))}
        </Steps>

        <div style={{
          flex: 1,
          overflow: 'hidden',
          paddingRight: '8px',
          marginTop: '18px',
          marginBottom: '60px',
          position: 'relative',
          height: 'calc(100vh - 250px)'
        }}>
          <div style={{ minHeight: '600px', height: '100%' }}>
            {showValidationAlert && (
              <Alert
                message={intl.formatMessage({ id: 'pages.order.validation.title' })}
                style={{ marginTop: '16px' }}
                description={
                  <ul style={{ marginBottom: 0 }}>
                    {validationErrors.map((error, index) => (
                      <li key={index}>{error}</li>
                    ))}
                  </ul>
                }
                type="error"
                showIcon
                closable
                onClose={() => setShowValidationAlert(false)}
              />
            )}
            {steps[currentStep].content}
          </div>
        </div>
        <div style={{
          position: 'absolute',
          bottom: '24px', // 与Card的padding保持一致
          left: '24px',
          right: '24px',
          padding: '16px 0',
          backgroundColor: '#fff',
          borderTop: '1px solid #f0f0f0',
          textAlign: 'right'
        }}>
          {currentStep > 0 && (
            <Button style={{ marginRight: '8px' }} onClick={prevStep}>
              <FormattedMessage id="pages.button.previous" />
            </Button>
          )}
          {currentStep < steps.length - 1 ? (
            <Button type="primary" onClick={nextStep}>
              <FormattedMessage id="pages.button.next" />
            </Button>
          ) : (
              <Button type="primary" onClick={submitOrder} disabled={ !canSubmit || submitting || dataChanged }>
                {intl.formatMessage({ id: 'pages.order.submit' })}
              {/* {submitting
                ? intl.formatMessage({ id: 'pages.order.submitting' })
                : intl.formatMessage({ id: 'pages.order.submit' })
              } */}
            </Button>
          )}
        </div>
      </Card>
    </div>
  );
};

export default CreateOrderPage;